package com.mumu.xiaodu

import android.app.ActivityManager
import android.content.Context
import android.os.Debug
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.webkit.WebView
import java.lang.ref.WeakReference

/**
 * 内存管理器 - 防止内存泄露和监控内存使用
 * 专为自用Demo设计，提供最大化的内存管理能力
 */
class MemoryManager private constructor() {
    
    companion object {
        private const val TAG = "MemoryManager"
        private const val MEMORY_CHECK_INTERVAL = 30000L // 30秒检查一次
        private const val MEMORY_THRESHOLD_MB = 150 // 内存阈值150MB
        
        @Volatile
        private var INSTANCE: MemoryManager? = null
        
        fun getInstance(): MemoryManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: MemoryManager().also { INSTANCE = it }
            }
        }
    }
    
    private val handler = Handler(Looper.getMainLooper())
    private var contextRef: WeakReference<Context>? = null
    private var isMonitoring = false
    private val webViewRefs = mutableSetOf<WeakReference<WebView>>()
    
    private val memoryCheckRunnable = object : Runnable {
        override fun run() {
            checkMemoryUsage()
            handler.postDelayed(this, MEMORY_CHECK_INTERVAL)
        }
    }
    
    /**
     * 初始化内存管理器
     */
         fun initialize(context: Context) {
         contextRef = WeakReference(context)
         startMemoryMonitoring()
         
         // 启用严格模式 - 自用Demo版本
         try {
             enableStrictMode()
         } catch (e: Exception) {
             Log.w(TAG, "StrictMode initialization skipped", e)
         }
         
         Log.d(TAG, "MemoryManager initialized with maximum permissions")
     }
    
    /**
     * 开始内存监控
     */
    private fun startMemoryMonitoring() {
        if (!isMonitoring) {
            isMonitoring = true
            handler.post(memoryCheckRunnable)
            Log.d(TAG, "Memory monitoring started")
        }
    }
    
    /**
     * 停止内存监控
     */
    fun stopMemoryMonitoring() {
        if (isMonitoring) {
            isMonitoring = false
            handler.removeCallbacks(memoryCheckRunnable)
            Log.d(TAG, "Memory monitoring stopped")
        }
    }
    
    /**
     * 检查内存使用情况
     */
    private fun checkMemoryUsage() {
        val context = contextRef?.get() ?: return
        
        try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            
            // 获取当前进程内存使用情况
            val debugMemoryInfo = Debug.MemoryInfo()
            Debug.getMemoryInfo(debugMemoryInfo)
            
            val totalPssKb = debugMemoryInfo.totalPss
            val totalPssMb = totalPssKb / 1024
            
            Log.d(TAG, "Memory usage: ${totalPssMb}MB (PSS), Available: ${memoryInfo.availMem / (1024 * 1024)}MB")
            
            // 如果内存使用超过阈值，执行清理
            if (totalPssMb > MEMORY_THRESHOLD_MB) {
                performMemoryCleanup()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "Error checking memory usage", e)
        }
    }
    
    /**
     * 执行内存清理
     */
    private fun performMemoryCleanup() {
        Log.w(TAG, "Memory usage high, performing cleanup...")
        
        try {
            // 清理WebView缓存
            cleanupWebViews()
            
            // 强制垃圾回收
//            System.gc()
            
            // 建议系统回收内存
            val context = contextRef?.get()
            if (context != null) {
                try {
                    val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
                    // 使用安全的内存管理方法
                    Runtime.getRuntime().gc()
                    System.runFinalization()
                } catch (e: Exception) {
                    Log.w(TAG, "Standard memory cleanup used", e)
                }
            }
            
            Log.d(TAG, "Memory cleanup completed")
            
        } catch (e: Exception) {
            Log.e(TAG, "Error during memory cleanup", e)
        }
    }
    
    /**
     * 注册WebView用于内存管理
     */
    fun registerWebView(webView: WebView) {
        webViewRefs.add(WeakReference(webView))
        Log.d(TAG, "WebView registered for memory management")
    }
    
    /**
     * 从内存管理器中移除WebView
     */
    fun unregisterWebView(webView: WebView) {
        val iterator = webViewRefs.iterator()
        while (iterator.hasNext()) {
            val webViewRef = iterator.next()
            if (webViewRef.get() == webView) {
                iterator.remove()
                Log.d(TAG, "WebView unregistered from memory management")
                break
            }
        }
    }
    
    /**
     * 清理WebView相关资源
     */
    private fun cleanupWebViews() {
        val iterator = webViewRefs.iterator()
        while (iterator.hasNext()) {
            val webViewRef = iterator.next()
            val webView = webViewRef.get()
            
            if (webView == null) {
                // WebView已被回收，移除引用
                iterator.remove()
            } else {
                                 try {
                     // 清理WebView缓存
                     webView.clearCache(true)
                     webView.clearHistory()
                     webView.clearFormData()
                     
                     // 现代WebView内存清理方法
                     webView.onPause()
                     webView.onResume()
                     
                     Log.d(TAG, "WebView cache cleared")
                 } catch (e: Exception) {
                     Log.e(TAG, "Error clearing WebView cache", e)
                 }
            }
        }
    }
    
         /**
      * 启用StrictMode - 优化配置，避免过度检测
      */
     private fun enableStrictMode() {
         try {
             // 🚀 优化的 StrictMode 配置 - 允许必要的磁盘操作
             android.os.StrictMode.setThreadPolicy(
                 android.os.StrictMode.ThreadPolicy.Builder()
                     .detectNetwork() // 检测网络操作
                     .detectCustomSlowCalls() // 检测自定义慢操作
                     // 移除 detectDiskReads() 和 detectDiskWrites() 以避免合理的缓存操作被标记
                     .penaltyLog() // 仅记录日志，不终止应用
                     .build()
             )
             
             android.os.StrictMode.setVmPolicy(
                 android.os.StrictMode.VmPolicy.Builder()
                     .detectLeakedSqlLiteObjects()
                     .detectLeakedClosableObjects()
                     .detectLeakedRegistrationObjects()
                     .detectActivityLeaks()
                     .detectFileUriExposure()
                     // 移除一些过于严格的检测
                     .penaltyLog()
                     .build()
             )
             
             Log.d(TAG, "StrictMode enabled with optimized configuration for TV browser")
         } catch (e: Exception) {
             Log.e(TAG, "Failed to enable StrictMode", e)
         }
     }
    
    /**
     * 获取内存使用统计
     */
    fun getMemoryStats(): String {
        return try {
            val debugMemoryInfo = Debug.MemoryInfo()
            Debug.getMemoryInfo(debugMemoryInfo)
            
            val totalPssKb = debugMemoryInfo.totalPss
            val totalPssMb = totalPssKb / 1024
            val dalvikPssMb = debugMemoryInfo.dalvikPss / 1024
            val nativePssMb = debugMemoryInfo.nativePss / 1024
            val otherPssMb = debugMemoryInfo.otherPss / 1024
            
            """
            Memory Stats:
            Total: ${totalPssMb}MB
            Dalvik: ${dalvikPssMb}MB
            Native: ${nativePssMb}MB
            Other: ${otherPssMb}MB
            WebViews: ${webViewRefs.size}
            """.trimIndent()
            
        } catch (e: Exception) {
            "Memory stats unavailable: ${e.message}"
        }
    }
    
    /**
     * 手动触发内存清理
     */
    fun forceMemoryCleanup() {
        Log.d(TAG, "Manual memory cleanup triggered")
        performMemoryCleanup()
    }
    
    /**
     * 销毁内存管理器
     */
    fun destroy() {
        stopMemoryMonitoring()
        webViewRefs.clear()
        contextRef = null
        Log.d(TAG, "MemoryManager destroyed")
    }
} 